package com.thinkgem.jeesite.modules.sys.web;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.*;
import com.thinkgem.jeesite.modules.sys.service.*;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jyy on 2016/10/19 0019.
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/orderProduct")
public class TbOrderController extends BaseController {

    @Autowired
    private TbOrderService tbOrderService;
    @Autowired
    private TbProductService tbProductService;
    @Autowired
    private TbCategoryService tbCategoryService;
    @Autowired
    private TbOrderProductService tbOrderProductService;
    @Autowired
    private UserService userService;
    @Autowired
    private TbMsgNotifyService tbMsgNotifyService;
    @Autowired
    private TbAgentProductService tbAgentProductService;
    @Autowired
    private TbUserVerifyService tbUserVerifyService;

    // 查询进货店铺信息
    @RequestMapping(value = {"orderProductList", ""})
    public String OrderList(TbOrder tbOrder,
                            HttpServletRequest request, HttpServletResponse response, Model model) {

     /*   tbOrder.setBeginDate(DateUtils.parseDate(beginDate11));
        tbOrder.setEndDate(DateUtils.parseDate(endDate11));*/
        String uid = UserUtils.getUser().getId();
        tbOrder.setUid(uid);
        Page<TbOrder> page = tbOrderService.findTbOrderByPage(new Page<TbOrder>(request, response), tbOrder);
        model.addAttribute("page", page);
        if(page.getList().size()==0){
            model.addAttribute("message1","无查询结果");
        }
        return "modules/sys/orderProductList";
    }
    /**
     * 导出进货订单
     * @return
     */
    @RequestMapping(value = "exportTenement", method= RequestMethod.POST)
    public String exportTenementFile(TbOrder tbOrder,
                                     @RequestParam(value = "beginDate11", required = false) String beginDate11,
                                     @RequestParam(value = "endDate11", required = false) String endDate11,
                                     HttpServletRequest request, HttpServletResponse response,
                                     RedirectAttributes redirectAttributes,Model model) {
        tbOrder.setBeginDate(DateUtils.parseDate(beginDate11));
        tbOrder.setEndDate(DateUtils.parseDate(endDate11));
        String uid = UserUtils.getUser().getId();
        tbOrder.setUid(uid);
        try {
            String fileName = "进货订单"+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<TbOrder> page = tbOrderService.exportTenement(new Page<TbOrder>(request, response), tbOrder);
            new ExportExcel("进货订单", TbOrder.class).setDataList(page.getList()).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导出进货订单失败！失败信息："+e.getMessage());
        }
        return "redirect:" + adminPath + "/sys/orderProduct/orderProductList";
    }

    // 查看进货订单信息
    @RequestMapping(value = "queryOrder/{orderId}")
    public String queryOrderProduct(@PathVariable("orderId") Integer orderId, Model model) {
        TbOrder tbOrder = tbOrderService.queryOrder(orderId);
        model.addAttribute("tbOrder", tbOrder);
        //如果是海外购订单，则跳转到另一个页面，这个页面会将微信端用户下的订单展现出来
        //在展示页面在点击发货，从而输入物流信息
        if(null!=tbOrder&&"2".equals(tbOrder.getExtraParam())){
            //showurl中存储的是，海外购订单中微信用户下的订单的id
            String orderIds=tbOrder.getShowUrl();
            if(null!=orderId&&!"".equals(orderIds)){
                orderIds=orderIds.substring(0,orderIds.length()-1);
            }
            List<TbOrder> seaList=tbOrderService.selectOrderListById(orderIds);
            //overseaSendList.jsp
            model.addAttribute("orderlist", seaList);
            model.addAttribute("oversea",1);
            //将店铺下的海外购的订单的id存储，全部发货后返回进货订单页面
            model.addAttribute("orderId",orderId);
            return "modules/sys/overseaSendList";
        }else{
            List<TbOrderProduct> tbOrderProductList = tbOrderProductService.queryTbOrderProducts(orderId);
            if(!CollectionUtils.isEmpty(tbOrderProductList)){
                TbProduct tbProduct = tbProductService.selectByPrimaryKey(tbOrderProductList.get(0).getProductId());
                TbCategory tbCategory = tbCategoryService.getTbCategory(tbProduct.getCategoryId());
                String categoryId = tbCategory.getParentIds().substring(4,5);
                if("3".equals(categoryId)){
                    model.addAttribute("flag","1");
                }else if("2".equals(categoryId)){
                    model.addAttribute("flag","2");
                    model.addAttribute("oversea",1);
                }else{
                    model.addAttribute("flag","0");
                }
            }

            model.addAttribute("tbOrderProductList", tbOrderProductList);
            return "modules/sys/orderProductQuery";
        }

    }
    @RequestMapping(value = "userVerify/{orderId}")
    public String userVerify(@PathVariable("orderId") Integer orderId, Model model) {
        //根据订单id得到订单信息，订单信息中有用户的id信息，已用户id信息查询实名认证信息
        TbOrder tbOrder = tbOrderService.queryOrder(orderId);
        if(null!=tbOrder){
            //根据id得到用户实名认证的身份证正面和反面信息
            String uid=tbOrder.getUid();
            TbUserVerify tbUserVerify=tbUserVerifyService.getVerifyById(uid);
            model.addAttribute("mobile",tbOrder.getContactMobile());
            model.addAttribute("uname",tbOrder.getContactName());
            model.addAttribute("tbUserVerify",tbUserVerify);
        }else{
            model.addAttribute("tbUserVerify",new TbUserVerify());
            model.addAttribute("mess","此订单的用户没有实名认证的身份证信息！");
        }

        return "modules/sys/agentCheckUserVerfiy";
    }
    // 海外购发货的页面
    @RequestMapping(value = "overseaqueryOrder/{orderId}")
    public String overseaqueryOrder(@PathVariable("orderId") Integer orderId,Integer shopProId, Model model) {
        //如果为海外购订单的最后一笔订单，点击发货后，则将进货订单改为已关闭状态
        TbOrder tbOrder = tbOrderService.queryOrder(orderId);

        List<TbOrderProduct> tbOrderProductList = tbOrderProductService.queryTbOrderProducts(orderId);
        if(!CollectionUtils.isEmpty(tbOrderProductList)){
            TbProduct tbProduct = tbProductService.selectByPrimaryKey(tbOrderProductList.get(0).getProductId());
            TbCategory tbCategory = tbCategoryService.getTbCategory(tbProduct.getCategoryId());
            String categoryId = tbCategory.getParentIds().substring(4,5);
            if("3".equals(categoryId)){
                model.addAttribute("flag","1");
            }else if("2".equals(categoryId)){
                model.addAttribute("flag","2");
                model.addAttribute("oversea",1);
                model.addAttribute("shopProId",shopProId);
            }else{
                model.addAttribute("flag","0");
            }
        }
        //tborder的id查询得到地址，作为海外购的发货地址
        tbOrder.setAddress(tbOrderService.queryAddress(tbOrder));
        model.addAttribute("tbOrder", tbOrder);
        model.addAttribute("tbOrderProductList", tbOrderProductList);
        return "modules/sys/overseaOrderProductQuery";

    }

    // 代理商果蔬预定管理
    @RequestMapping(value = "reserveProduct/{channel}")
    public String reserveProduct(TbOrder tbOrder,@PathVariable("channel") Integer channel,HttpServletRequest request, HttpServletResponse response, Model model) {
        String uid = UserUtils.getUser().getId();
        tbOrder.setUid(uid);
        tbOrder.setChannelId(channel);
        Page<TbOrder> reservePage = tbOrderService.findReserveByPage(new Page<TbOrder>(request, response), tbOrder);
        model.addAttribute("reservePage", reservePage);
        return "modules/sys/reserveProductList";
    }

    // 代理商下的店铺预定订单信息
    @RequestMapping(value = "reserveQueryOrder/{orderId}")
    public String queryReserveProduct(@PathVariable("orderId") Integer orderId, Model model) {
        TbOrder reserveTbOrder = tbOrderService.queryOrder(orderId);
        model.addAttribute("reserveTbOrder", reserveTbOrder);

        List<TbOrderProduct> reserveTbOrderProductList = tbOrderProductService.queryTbOrderProducts(orderId);
        model.addAttribute("reserveTbOrderProductList", reserveTbOrderProductList);
        return "modules/sys/reserveProductQuery";
    }

    // 用户果蔬预定列表
    @RequestMapping(value = "showGardenStuff")
    public String queryGardenStuff(TbOrder tbOrder, HttpServletRequest request, HttpServletResponse response, Model model) {
        String uid = UserUtils.getUser().getId();
        tbOrder.setUid(uid);
        Page<TbOrder> userGardenStuffPage = tbOrderService.findUserReserveByPage(new Page<TbOrder>(request, response), tbOrder);
        model.addAttribute("userGardenStuffPage", userGardenStuffPage);

        return "modules/sys/showGardenStuffList";
    }

    // 用户果蔬预定订单信息
    @RequestMapping(value = "reserveUserOrderU/{orderId}")
    public String queryReserveGardenStuff(@PathVariable("orderId") Integer orderId, Model model) {
        TbOrder reserveTbOrder = tbOrderService.queryOrder(orderId);
        model.addAttribute("reserveTbOrder", reserveTbOrder);
        List<TbOrderProduct> reserveTbOrderProductList = tbOrderProductService.queryTbOrderProducts(orderId);
        model.addAttribute("reserveTbOrderProductList", reserveTbOrderProductList);
        return "modules/sys/reserveUserOrderQuery";
    }
    // 修改用户果蔬预定订单状态的页面展示
    @RequestMapping(value = "editUserOrderU/{orderId}")
    public String editGardenStuff(@PathVariable("orderId") Integer orderId, Model model) {
         TbOrder reserveTbOrder = tbOrderService.queryOrder(orderId);
         model.addAttribute("tbOrder", reserveTbOrder);
        List<TbOrderProduct> reserveTbOrderProductList = tbOrderProductService.queryTbOrderProducts(orderId);
        model.addAttribute("editTbOrderProductList", reserveTbOrderProductList);
        model.addAttribute("endlen",reserveTbOrderProductList.size());
        return "modules/sys/editGudenStuffState";
    }
    // 果蔬预定订单状态的修改
    @RequestMapping(value = "editGudenStuffState")
    public String editReserveGardenStuff(String id,String state,Model model) {
        Map map=new HashMap();
        map.put("orderState",state);
        map.put("id",id);
        if(state!=null){
            if(StringUtils.isNotBlank(state+"")&&state!=null){
                if(Global.isDemoMode()){
                    model.addAttribute("message", "演示模式，不允许操作！");
                    return "modules/sys/editShoppingOrderState";
                }
                try{
                    tbOrderService.editGudenStuffState(map);
                    model.addAttribute("message", "修改订单状态成功");
                }catch (Exception e){
                    model.addAttribute("message", "修改订单状态失败");
                }
            }
        }
        int orderId=Integer.parseInt(id);
        TbOrder reserveTbOrder = tbOrderService.queryOrder(orderId);
        model.addAttribute("tbOrder", reserveTbOrder);
        List<TbOrderProduct> reserveTbOrderProductList = tbOrderProductService.queryTbOrderProducts(orderId);
        model.addAttribute("editTbOrderProductList", reserveTbOrderProductList);
        model.addAttribute("endlen",reserveTbOrderProductList.size());
        return "modules/sys/editGudenStuffState";

    }
    // 确认收款
    @RequestMapping(value = "editInputOrderU/{orderId}")
    public String editInputOrderProduct(@PathVariable("orderId") Integer id,HttpServletRequest request, Model model) {
        Map map=new HashMap();
        map.put("orderState","2");
        map.put("payState","1");
        map.put("payId",request.getParameter("payId"));
        map.put("payTime",new Date());
        map.put("id",id);
        if(Global.isDemoMode()){
            model.addAttribute("message", "演示模式，不允许操作！");
            return "modules/sys/editShoppingOrderState";
        }
        try{
            tbOrderService.editGudenStuffState(map);
            model.addAttribute("message", "确认收款成功");
        }catch (Exception e){
            model.addAttribute("message", "确认收款失败");
        }
        return "forward:" + adminPath + "/sys/orderProduct/orderProductList";
    }
    //查看明细
    @RequestMapping(value = "editInputOrderPro/{orderId}")
    public String editInputOrderProduct(@PathVariable("orderId") Integer orderId, Model model) {
        TbOrder reserveTbOrder = tbOrderService.queryOrder(orderId);
        model.addAttribute("tbOrder", reserveTbOrder);
        List<TbOrderProduct> reserveTbOrderProductList = tbOrderProductService.queryTbOrderProducts(orderId);
        if(!CollectionUtils.isEmpty(reserveTbOrderProductList)){
            TbProduct tbProduct = tbProductService.selectByPrimaryKey(reserveTbOrderProductList.get(0).getProductId());
            TbCategory tbCategory = tbCategoryService.getTbCategory(tbProduct.getCategoryId());
            String categoryId = tbCategory.getParentIds().substring(4,5);
            if("3".equals(categoryId)){
                model.addAttribute("flag","1");
            }else{
                model.addAttribute("flag","0");
            }
        }
        model.addAttribute("editTbOrderProductList", reserveTbOrderProductList);
        model.addAttribute("endlen",reserveTbOrderProductList.size());
        return "modules/sys/editOrderProductState";
    }
    @RequestMapping(value = "editOrderProductState")
    public String editOrderProductState(String id,String state,String logisticsNumber,String arriveTime,String logisticsCode,String showUrl,String oversea,Integer shopId,Model model) {
        Map map=new HashMap();
        map.put("orderState",state);
        map.put("id",id);
        map.put("logisticsNumber",logisticsNumber);
        map.put("logisticsCode",logisticsCode);

        int fahuo=0;
        String  name="";
        int orderId=Integer.parseInt(id);
        //确认发货的同时，要修改代理商商品表的库存
        List<TbOrderProduct> tbOrderProductList = tbOrderProductService.queryTbOrderProducts(orderId);
        if(!CollectionUtils.isEmpty(tbOrderProductList)){
            for(int i=0;i<tbOrderProductList.size();i++){
                TbOrderProduct  tbOrderProduct=tbOrderProductList.get(i);
                TbProduct tbProduct = tbProductService.selectByPrimaryKey(tbOrderProduct.getProductId());
                TbCategory tbCategory = tbCategoryService.getTbCategory(tbProduct.getCategoryId());
                String categoryId = tbCategory.getParentIds().substring(4,5);
                if(categoryId!=null&&!"".equals(categoryId)&&"4".equals(categoryId)){//3是生活预定4，是便利生活
                    //根据id得到代理商商品
                    TbAgentProduct tbAgentProduct=tbAgentProductService.selectById(tbOrderProduct.getAgentProductId()+"");
                    //如果订单数量小于代理商库存，则不让发货，提示库存不足，不能发货
                    if(tbAgentProduct.getStoreNum()<tbOrderProduct.getQuantity()){
                        fahuo=1;
                        name=tbOrderProduct.getProductName();
                    }

                }

            }
        }
        String isok="1";
        //库存不足的情况下，不可以发货
        if(fahuo==1){
            model.addAttribute("message1","商品"+name+"库存不足，不能进行发货，请您补货！");
        }else{

            if(state!=null){
                if(StringUtils.isNotBlank(state+"")&&state!=null){
                    if(Global.isDemoMode()){
                        model.addAttribute("message", "演示模式，不允许操作！");
                        return "modules/sys/editOrdrProductState";
                    }
                    try{
                        //将订单状态改为发货状态，并将物流单号写进去
                        tbOrderService.editGudenStuffState(map);
                        TbOrder seatbOrder = tbOrderService.queryOrder(shopId);
                        String orderIds=seatbOrder.getShowUrl();
                        if(null!=id&&!"".equals(orderIds)){
                            orderIds=orderIds.substring(0,orderIds.length()-1);
                            String[] ide=orderIds.split(",");
                            String idse=ide[ide.length-1];
                            if((id).equals(idse)){//如果订单id为订单id数组的最后一个相同，则将订单状态改为已关闭
                                Map map1=new HashMap();
                                map1.put("orderState",6);//6为已关闭的订单状态
                                map1.put("id",shopId);
                                tbOrderService.editGudenStuffState(map1);
                                isok="2";
                            }

                        }

                        model.addAttribute("message", "修改订单状态成功");
                    }catch (Exception e){
                        model.addAttribute("message", "修改订单状态失败");
                    }
                    if(!CollectionUtils.isEmpty(tbOrderProductList)){
                        for(int i=0;i<tbOrderProductList.size();i++){
                            TbOrderProduct  tbOrderProduct=tbOrderProductList.get(i);
                            TbProduct tbProduct = tbProductService.selectByPrimaryKey(tbOrderProduct.getProductId());
                            TbCategory tbCategory = tbCategoryService.getTbCategory(tbProduct.getCategoryId());
                            String categoryId = tbCategory.getParentIds().substring(4,5);
                            if(categoryId!=null&&!"".equals(categoryId)&&"4".equals(categoryId)){//3是生活预定4，是便利生活
                                //代理商减库存
                                Integer rows=tbOrderService.subStoreNum(tbOrderProduct);
                                //根据id得到代理商商品
                                TbAgentProduct tbAgentProduct=tbAgentProductService.selectById(tbOrderProduct.getAgentProductId()+"");
                                //库存预警值
                                if(null!=tbAgentProduct&&null!=tbAgentProduct.getAlertStoreNum()&&tbAgentProduct.getAlertStoreNum()>tbAgentProduct.getStoreNum()){
                                    TbMsgNotify tbMsgNotify=new TbMsgNotify();
                                    //【开心果】库存量仅有-4件，请补充库存
                                    tbMsgNotify.setUid(UserUtils.getUser().getId());
                                    tbMsgNotify.setTitle("库存不足提醒");
                                    tbMsgNotify.setContent("【"+tbProduct.getTitle()+"】的数量低于预警值，仅有"+tbAgentProduct.getStoreNum()+"请及时补充！");
                                    tbMsgNotify.setStatus("0");
                                    Date da=new Date();
                                    tbMsgNotify.setCreateTime(da);
                                    tbMsgNotify.setUpdateTime(da);
                                    tbMsgNotifyService.insertMsg(tbMsgNotify);
                                }

                            }

                        }
                    }
                }
            }
        }
        TbOrder reserveTbOrder = tbOrderService.queryOrder(orderId);
        model.addAttribute("tbOrder", reserveTbOrder);
        List<TbOrderProduct> reserveTbOrderProductList = tbOrderProductService.queryTbOrderProducts(orderId);
        if(!CollectionUtils.isEmpty(reserveTbOrderProductList)){
            TbProduct tbProduct = tbProductService.selectByPrimaryKey(reserveTbOrderProductList.get(0).getProductId());
            TbCategory tbCategory = tbCategoryService.getTbCategory(tbProduct.getCategoryId());
            String categoryId = tbCategory.getParentIds().substring(4,5);
            if("3".equals(categoryId)){//3是生活预定4，是便利生活
                model.addAttribute("flag","1");
            }else{
                model.addAttribute("flag","0");
            }
        }
        //oversea=1为海外购，shopProId为店铺进货的订单id，由此确定发货物品为海外购
        if("1".equals(oversea)&&null!=shopId&&"1".equals(isok)){
            model.addAttribute("editTbOrderProductList", reserveTbOrderProductList);
            model.addAttribute("endlen",reserveTbOrderProductList.size());
            return "forward:" + adminPath + "/sys/orderProduct/queryOrder/"+shopId;
        }else{
            model.addAttribute("editTbOrderProductList", reserveTbOrderProductList);
            model.addAttribute("endlen",reserveTbOrderProductList.size());
            return "forward:" + adminPath + "/sys/orderProduct/orderProductList";
        }

    }
}
